<template>
  <div class="app-container">
    <br>
     <el-form :model="templateForm" ref="templateForm" label-width="80px" :rules="templateFormRules">
      <el-row :gutter=10>
        <h3>模板信息</h3>
        <el-col :span=6>
          <el-form-item label="模板名称" prop="templateName" >
            <el-input v-model="templateForm.templateName" :disabled="isInfo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <br>
    <el-button type="primary" @click="add({root: true})" :disabled="isInfo">添加根类</el-button>
    <br>
    <br>
    <el-table v-loading="listLoading" :data="treeData" style="width: 100%;margin-bottom: 20px;" row-key="id" border  :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-expand-all="true" :indent=60>
      <el-table-column prop="name" label="一级名称"  width="250" ></el-table-column>
      <el-table-column label="操作" width="240" align="center">
        <template slot-scope="scope" >
          <div style="display: flex;flex-direction: row;justify-content: right;padding-left: 10px;padding-right: 15px;">
            <el-button type="primary" v-if="scope.row.level != 3"  @click="add(scope.row)" size="small" :disabled="isInfo">新增子项</el-button>
            <el-button type="success"  @click="update(scope.row)" size="small" :disabled="isInfo">修改</el-button>
            <el-button type="danger" @click="deleteInfo(scope)" size="small" :disabled="isInfo">删除</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="200" align="center">
        <template slot-scope="scope" >
          <el-button  @click="move(scope.row, 1)" size="small" :disabled="isInfo">上移</el-button>
          <el-button  @click="move(scope.row, 2)" size="small" :disabled="isInfo">下移</el-button>
        </template>
      </el-table-column>
    </el-table>
    

    <div class="footer">
      <el-button type="primary" :loading="commitBtnLoading" @click="templateConfirm" :disabled="isInfo">提交</el-button>
      <div style="width:100px;display: inline-block;"> </div>
      <el-button @click="templateCancel">取 消</el-button>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false">
      <h2>模板信息</h2>
      <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
        <el-form-item label="上级id" v-if="false">
            <el-input v-model="form.id" :disabled="true" />
        </el-form-item>
        <el-form-item label="上级名称" v-if="form.parentId">
            <el-input v-model="form.parentName" :disabled="true" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
  </el-dialog>
  </div>
</template>

<script>
let id = 1000;

import { getTreeList, add, edit, del, editTemplateName } from '@/api/visitTemplate'
import { getList as getJobOfficeList } from '@/api/jobOffice'

export default {
  name: "VisitTemplate",
  filters: {
    
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    }
    return {
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      templateForm: {},
      form: {},
      formVisible: false,
      treeData: [],
      dialogTitle: '类型详情',
      templateFormRules: {
        templateName: [{ required: true, trigger: 'blur', validator: validateName }],
      },
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }]
      },
      commitBtnLoading: false,
      isInfo: false,
      paramVisitTemplate: undefined,
    }
  },
  created() {
    document.getelement
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.templateForm = this.$route.params
      console.log(this.templateForm)
      if(!this.templateForm) {
        this.listLoading = false
        return
      }
      getTreeList({templateCode: this.templateForm.templateCode}).then(res=> {
        console.log(res)
        this.isInfo = this.templateForm.isInfo
        this.treeData = res.data
        if(res.data.length != 0) {
          this.$set(this.templateForm, 'templateCode', res.data[0].templateCode)
          this.$set(this.templateForm, 'templateName', res.data[0].templateName)
        }
        this.listLoading = false
      }).catch(err=>{
        console.log(err)
      })
    },
    update(row) {
      if(!this.templateForm.templateName) {
        this.$message.error('请先输入模板名称')
        return;
      }
      this.reset()
      this.dialogTitle = '修改模板项目'
      this.form = JSON.parse(JSON.stringify(row))
      this.formVisible = true
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该项目?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          getTreeList({templateCode: this.paramVisitTemplate.templateCode}).then(res=> {
            console.log(res)
            this.treeData = res.data
          }).catch(err=>{
            console.log(err)
          })
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      console.log(row)
      if(!this.templateForm.templateName) {
        this.$message.error('请先输入模板名称')
        return;
      }
      this.reset()
      this.dialogTitle = '添加模板选项'
      this.form.parentId = row.root ? 0 : row.id
      this.form.parentName = row.name
      this.form.sort = row.root ? this.treeData.length+1 : (row.children ? row.children.length+1 : 1)
      this.form.level = row.root ? 1 : row.level + 1
      console.log(this.form)
      this.formVisible = true
    },
    confirm() {
      this.listLoading = true
      console.log(this.form)
      this.$refs.templateForm.validate(valid => {
        if (valid) {
          var typeObj = this.form
          typeObj.parentId = this.form.parentId ? this.form.parentId : 0
          typeObj.templateName = this.templateForm.templateName
          typeObj.templateCode = this.templateForm.templateCode
          if(this.form.id) {
            edit(typeObj).then(res=>{
              console.log(res)
              this.templateForm.templateCode = res.data.templateCode
              getTreeList({templateCode: this.templateForm.templateCode}).then(ListRes=> {
                console.log(ListRes)
                this.treeData = ListRes.data
                this.formVisible = false
                this.listLoading = false
              }).catch(err=>{
                console.log(err)
              })
              this.formVisible = false
            })
          } else {
            add(typeObj).then(res=>{
              console.log(res)
              this.templateForm.templateCode = res.data.templateCode
              getTreeList({templateCode: this.templateForm.templateCode}).then(ListRes=> {
                console.log(ListRes)
                this.treeData = ListRes.data
                this.formVisible = false
                this.listLoading = false
              }).catch(err=>{
                console.log(err)
              })
            }).catch(err=>{
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    templateCancel() {
      console.log(this.node)
      this.$router.push({name: 'VisitTemplateList'})
    },
    reset() {
      this.form = {}
    },
    cancel() {
      this.form = {}
      this.formVisible = false
    },
    move(row, type) {
      this.listLoading = true
      var curList = this.getParentList(row, this.treeData)
      var rowIndex = curList.indexOf(row)
      if(type === 1) {
        // 上移
        if(rowIndex === 0) {
          this.listLoading = false
          return
        }
        curList[rowIndex].sort--
        curList[rowIndex-1].sort++
        edit(curList[rowIndex-1]).then(res=>{
          edit(curList[rowIndex]).then(res=>{
            getTreeList({templateCode: this.templateForm.templateCode}).then(ListRes=> {
              this.treeData = ListRes.data
              this.listLoading = false
            }).catch(err=>{
              console.log(err)
            })
          })
        })
      } else {
        // 下移
        if(rowIndex === curList.length-1) {
          this.listLoading = false
          return
        }
        curList[rowIndex+1].sort--
        edit(curList[rowIndex+1]).then(res=>{
          curList[rowIndex].sort++
          edit(curList[rowIndex]).then(res=>{
            getTreeList({templateCode: this.templateForm.templateCode}).then(ListRes=> {
              this.treeData = ListRes.data
              this.listLoading = false
            }).catch(err=>{
              console.log(err)
            })
          })
        })
      }
    },
    getParentList(row, treeData) {
      for (const item of treeData) {
        if(item.level === row.level && item.name === row.name) {
          return treeData
        }
        if(item.children) {
          var list = this.getParentList(row, item.children)
          if(list) return list
        }
      }
    },
    templateConfirm() {
      editTemplateName(this.templateForm).then(res=> {
        console.log(res)
        this.$router.push({name: 'VisitTemplateList'})
      })
    }
  },
  
}
</script>


<style>


</style>